/*
#Copyright (c) 2013, Philippe Bordron <philippe.bordron@gmail.com>
#
# This file is part of SIPPER.
#
# DCC is free software: you can redistribute it and/or modify
# it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DCC is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU LESSER GENERAL PUBLIC LICENSE for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# along with SIPPER.  If not, see <http://www.gnu.org/licenses/>
*/
package combi.wip.sipper.io.metacyc;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;

import combi.sipper.io.InFlatFile;
import combi.wip.sipper.modeling.Protein;
import combi.wip.sipper.modeling.ProteinComplex;

public class IOProteinsFromMetaCyc {


	protected String fileProteins;

	protected static String COMPONENTS = "COMPONENTS";

	public IOProteinsFromMetaCyc(String fileProteins)
	{
		this.fileProteins = fileProteins;
	}


	private void addProtein(String p, Map<String, Protein> idProt, Map<String, Map<String, Collection<String>>> proteinsMap)
	{
		//System.err.println(p);
		if (proteinsMap.get(p) != null)
		{
			Collection<String> components = proteinsMap.get(p).get(COMPONENTS);
			if (components == null)
			{
				idProt.put(p, new Protein(p));
			}
			else{
				Collection<Protein> cplx = new HashSet<Protein>();
				for (String c : components)
				{
					addProtein(c, idProt, proteinsMap);
					cplx.add(idProt.get(c));
				}
				idProt.put(p, new ProteinComplex(p, cplx));
				//System.err.println(idProt.get(p));
			}
		}
		else
		{
			// when p does not exists in proteins, it's a compound.
			idProt.put(p, new Protein(p));
		}
	}

	public Map<String, Protein> load() throws IOException
	{
		Map<String, Protein> result = new HashMap<String, Protein>();
		InFlatFile proteinsIn = new InFlatFile(fileProteins);
		Map<String, Map<String, Collection<String>>> proteinsMap = new HashMap<String, Map<String, Collection<String>>>();
		proteinsMap = proteinsIn.readFile();
		for(Entry<String, Map<String, Collection<String>>> entry : proteinsMap.entrySet())
		{
			addProtein(entry.getKey(), result, proteinsMap);
		}
		return result;
	}

}
